<template>
  <div class="review-section">
    <h3 class="section-title">商品评价</h3>
    
    <!-- 评价统计 -->
    <div v-if="reviewStats" class="review-stats">
      <div class="stats-item">
        <div class="stats-number">{{ reviewStats.totalReviews }}</div>
        <div class="stats-label">总评价</div>
      </div>
      <div class="stats-item">
        <div class="stats-number">{{ reviewStats.averageRating.toFixed(1) }}</div>
        <div class="stats-label">平均评分</div>
      </div>
      <div class="stats-item">
        <div class="stats-rating">
          <span 
            v-for="i in 5" 
            :key="i" 
            class="star"
            :class="{ filled: i <= Math.round(reviewStats.averageRating) }"
          >
            ★
          </span>
        </div>
        <div class="stats-label">综合评分</div>
      </div>
    </div>

    <!-- 评价列表 -->
    <div v-if="reviews.length > 0" class="reviews-list">
      <div 
        v-for="review in reviews" 
        :key="review.id" 
        class="review-item"
      >
        <div class="review-header">
          <div class="reviewer-info">
            <div class="reviewer-name">{{ review.user?.username || '匿名用户' }}</div>
            <div class="review-date">{{ formatDate(review.createdAt) }}</div>
          </div>
          <div class="review-rating">
            <span 
              v-for="i in 5" 
              :key="i" 
              class="star"
              :class="{ filled: i <= review.rating }"
            >
              ★
            </span>
          </div>
        </div>
        <div class="review-content">{{ review.comment }}</div>
        
        <!-- 删除按钮 -->
        <div v-if="canDeleteReview(review)" class="review-actions">
          <el-button 
            type="danger" 
            size="small"
            @click="deleteReview(review.id)"
          >
            删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 无评价状态 -->
    <div v-else class="no-reviews">
      <div class="no-reviews-icon">📝</div>
      <div class="no-reviews-text">暂无评价</div>
    </div>

    <!-- 写评价表单 -->
    <div v-if="showReviewForm" class="review-form">
      <h4>写评价</h4>
      <div class="form-group">
        <label>评分</label>
        <div class="rating-input">
          <span 
            v-for="i in 5" 
            :key="i" 
            class="star clickable"
            :class="{ filled: i <= newReview.rating }"
            @click="newReview.rating = i"
          >
            ★
          </span>
        </div>
      </div>
      <div class="form-group">
        <label>评价内容</label>
        <el-input
          v-model="newReview.comment"
          type="textarea"
          :rows="4"
          placeholder="请分享您的使用体验..."
          :maxlength="500"
          show-word-limit
        />
      </div>
      <div class="form-actions">
        <el-button @click="cancelReview">
          取消
        </el-button>
        <el-button 
          type="primary"
          :loading="submitting"
          :disabled="!isValidReview"
          @click="submitReview"
        >
          {{ submitting ? '提交中...' : '提交评价' }}
        </el-button>
      </div>
    </div>

    <!-- 写评价按钮 -->
    <div class="write-review" v-if="!showReviewForm && canWriteReview">
      <el-button 
        type="primary"
        @click="showReviewForm = true"
      >
        写评价
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getProductReviews, createReview, deleteReview as deleteReviewApi, getReviewStats, checkUserReview } from '@/api/review'
import { ElMessage } from 'element-plus'

interface Review {
  id: number
  productId: number
  userId: number
  user?: {
    id: number
    username: string
  }
  rating: number
  comment: string
  createdAt: string
}

interface ReviewStats {
  totalReviews: number
  averageRating: number
  ratingDistribution: Record<number, number>
}

interface Props {
  productId: number
}

const props = defineProps<Props>()
const userStore = useUserStore()

// 响应式数据
const reviews = ref<Review[]>([])
const reviewStats = ref<ReviewStats | null>(null)
const showReviewForm = ref(false)
const submitting = ref(false)
const hasReviewed = ref(false)

const newReview = ref({
  rating: 5,
  comment: ''
})

// 计算属性
const isValidReview = computed(() => {
  return newReview.value.rating >= 1 && newReview.value.rating <= 5 && 
         newReview.value.comment.trim().length > 0
})

const canWriteReview = computed(() => {
  const canWrite = userStore.user && !hasReviewed.value
  console.log('canWriteReview:', {
    user: userStore.user,
    hasReviewed: hasReviewed.value,
    canWrite: canWrite
  })
  return canWrite
})

// 方法
const loadReviews = async () => {
  try {
    console.log('开始加载评价，商品ID:', props.productId)
    const response = await getProductReviews(props.productId, {
      page: 0,
      size: 10
    })
    if (response.data.success) {
      reviews.value = response.data.data.content || []
      console.log('评价加载成功:', reviews.value)
    } else {
      console.error('评价加载失败:', response.data.message)
    }
  } catch (error) {
    console.error('加载评价失败:', error)
  }
}

const loadReviewStats = async () => {
  try {
    console.log('开始加载评价统计，商品ID:', props.productId)
    const response = await getReviewStats(props.productId)
    if (response.data.success) {
      reviewStats.value = response.data.data
      console.log('评价统计加载成功:', reviewStats.value)
    }
  } catch (error) {
    console.error('加载评价统计失败:', error)
  }
}

const checkUserReviewed = async () => {
  if (!userStore.user) {
    console.log('用户未登录，跳过检查评价状态')
    return
  }
  
  try {
    console.log('检查用户评价状态，商品ID:', props.productId, '用户ID:', userStore.user.id)
    const response = await checkUserReview(props.productId, userStore.user.id)
    if (response.data.success) {
      hasReviewed.value = response.data.hasReviewed
      console.log('用户评价状态:', hasReviewed.value)
    }
  } catch (error) {
    console.error('检查用户评价状态失败:', error)
  }
}

const submitReview = async () => {
  if (!isValidReview.value) {
    ElMessage.warning('请填写有效的评价内容和评分！')
    return
  }
  if (!userStore.user) {
    ElMessage.warning('请先登录才能提交评价！')
    return
  }
  try {
    submitting.value = true
    const response = await createReview({
      productId: props.productId,
      userId: userStore.user.id,
      rating: newReview.value.rating,
      comment: newReview.value.comment.trim()
    })

    if (response.data.success) {
      showReviewForm.value = false
      newReview.value = { rating: 5, comment: '' }
      hasReviewed.value = true
      await loadReviews()
      await loadReviewStats()
      ElMessage.success('评价提交成功！')
    }
  } catch (error: any) {
    console.error('提交评价失败:', error)
    ElMessage.error(error.response?.data?.message || '提交评价失败，请重试')
  } finally {
    submitting.value = false
  }
}

const deleteReview = async (reviewId: number) => {
  if (!userStore.user || !confirm('确定要删除这条评价吗？')) return

  try {
    const response = await deleteReviewApi(reviewId, userStore.user.id)
    if (response.data.success) {
      await loadReviews()
      await loadReviewStats()
      ElMessage.success('评价删除成功！')
    }
  } catch (error: any) {
    console.error('删除评价失败:', error)
    ElMessage.error(error.response?.data?.message || '删除评价失败，请重试')
  }
}

const canDeleteReview = (review: Review) => {
  return userStore.user && review.userId === userStore.user.id
}

const cancelReview = () => {
  showReviewForm.value = false
  newReview.value = { rating: 5, comment: '' }
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 生命周期
onMounted(() => {
  if (props.productId) {
    loadReviews()
    loadReviewStats()
    checkUserReviewed()
  }
})
</script>

<style scoped>
.review-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.section-title {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.review-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.stats-item {
  text-align: center;
  min-width: 100px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #ff6b35;
  margin-bottom: 5px;
}

.stats-label {
  color: #666;
  font-size: 14px;
}

.stats-rating {
  margin-top: 10px;
}

.reviews-list {
  margin-bottom: 20px;
}

.review-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.reviewer-info {
  flex-grow: 1;
  margin-right: 15px;
}

.reviewer-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 5px;
}

.review-date {
  font-size: 12px;
  color: #999;
}

.review-rating {
  display: flex;
  gap: 3px;
}

.star {
  color: #ddd;
  font-size: 20px;
}

.star.filled {
  color: #ff6b35;
}

.review-content {
  color: #666;
  line-height: 1.6;
  margin-bottom: 10px;
}

.review-actions {
  margin-top: 10px;
}

.btn-small {
  padding: 8px 15px;
  font-size: 13px;
}

.btn-danger {
  background: #dc3545;
  color: #fff;
}

.btn-danger:hover {
  background: #c82333;
}

.no-reviews {
  text-align: center;
  padding: 40px;
  color: #666;
}

.no-reviews-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.review-form {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.review-form h4 {
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.rating-input {
  display: flex;
  gap: 5px;
}

.star.clickable {
  cursor: pointer;
  transition: color 0.3s ease;
}

.star.clickable:hover {
  color: #ff6b35;
}

textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  gap: 15px;
  justify-content: flex-end;
}

.write-review {
  text-align: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

.write-review-btn {
  padding: 12px 30px;
  font-size: 16px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: #ff6b35;
  color: #fff;
}

.btn-primary:hover:not(:disabled) {
  background: #e55a2b;
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-secondary {
  background: #6c757d;
  color: #fff;
}

.btn-secondary:hover {
  background: #5a6268;
}
</style> 